package com.chiaching.framwork.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.init.InitExecutor;
import com.chiaching.framwork.domian.constant.CoreConstant;
import com.chiaching.framwork.utils.IPUtils;
import com.chiaching.framwork.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CompositeFilter;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;

/**
 * @author jiajing.he
 * @date 2021/7/14 下午5:13
 */
@Configuration
@Slf4j
public class SentinelConfig {

    @PostConstruct
    public void initSentinel(){
        //设置公网ip
        String openIPAddress = IPUtils.openIPAddress();
        String nacosRegisterIp = System.getProperty(CoreConstant.SPRING_CLOUD_NACOS_DISCOVERY_IP);
        String sentinelRegisterIp = System.getProperty(CoreConstant.SPRING_CLOUD_SENTINEL_TRANSPORT_CLIENTIP);
        if (StringUtils.isNoneEmpty(openIPAddress)){
            if (StringUtils.isEmpty(nacosRegisterIp)){
                System.setProperty(CoreConstant.SPRING_CLOUD_NACOS_DISCOVERY_IP, openIPAddress);
            }
            if (StringUtils.isEmpty(sentinelRegisterIp)){
                System.setProperty(CoreConstant.SPRING_CLOUD_SENTINEL_TRANSPORT_CLIENTIP, openIPAddress);
            }
        }
        //主动初始化 ，让客户端连接sentinel控制台
        InitExecutor.doInit();
        log.info("do init sentinel success...");
    }


    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }


    @Bean
    public FilterRegistrationBean sentinelFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CompositeFilter());
        registration.addUrlPatterns("/*");
        registration.setName("sentinelFilter");
        registration.setOrder(1);
        return registration;
    }
}
